<?php

/**
 * Controlleur de base de gestion des actions
 *
 * @category   McCube
 * @package    Controller
 * @author     Leiha Sellier <leiha.sellier@gmail.com>
 * @license    http://creativecommons.org/licenses/by/3.0/  CC BY 3.0
 * @link       http://code.google.com/p/mechanics-cubes/
 */
class McCube_Controller{

    public $name           = '';
    public $bundle         = null;
    public $model          = null;
    public $tplEngine      = null;
    public $skeletonName       = 'skeleton.default';
    public $skeletonRender     = false;
    public $rootSkeletonRender = false;
    protected $_variables      = array();

    /** */
    public function __init(){}

    /** */
    public function __construct($name, $bundle){
        $this->name       = $name;
        $this->bundle     = $bundle;
        $this->route      = $this->session->getRouter()->getRoute();
        $this->tplEngine  = $bundle->getTplEngine();

        $this->addVar('session', $this->session);
        $this->__init();
    }

    public function __get($name){
        return $this->bundle->$name;
    }

    /** */
    public function runAction($action, $args=array()){
        if(!method_exists($this, $action))
            throw new McCube_Bundle_Exception('Controller:Action', 404, array(
                 'bundle' => $this->bundle->absoluteName
                ,'name' => $this->name.'/'.$action
            ));

        $this->action = $action;
        $render = $this->$action($args + $this->route);
        if($render === false)
            return;

        if(!$render)
            $render = $this->render();

        if($this->skeletonRender){
            $this->_variables['body'] = $render;
            $render = $this->tplEngine
                ->fetchFile($this->skeletonName, $this->_variables)
            ;
        }

        if($this->rootSkeletonRender){
            $this->_variables['body'] = $render;
            $render = McCube_Bundle::getBundle('/application')->getTplEngine()
                ->fetchFile($this->skeletonName, $this->_variables)
            ;
        }

        return $render;
    }

    /** */
    public function getHtmlHelper($name){
        $method = 'get'.ucfirst($name);
        return McCube_Html::$method();
        ;
    }


    /** */
    public function getForm($name){
        return $this->bundle->getForm($name, $this->name)
            ->setModel($this->model)
        ;
    }

    /** */
    public function addVar($name, $value){
        $this->_variables[$name] = $value;
    }

    /** */
    public function addLoop($name, $value){
        $this->tplEngine->addLoop($name, $value);
    }

    /** */
    public function render($tplName=null){
        if(is_null($tplName))
            $tplName = $this->action;

        $this->_variables['controller'] = $this;
        return $this->tplEngine
            ->fetchFile($this->name.DIRECTORY_SEPARATOR.$tplName , $this->_variables);
    }

}
